package fina2.dcs.returns;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.faces.context.FacesContext;
import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.jboss.annotation.ejb.LocalBinding;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.log.Log;
import org.jboss.seam.log.Logging;

import fina2.dcs.common.UIComponentHelper;
import fina2.dcs.context.ContextHelper;
import fina2.dcs.i18n.LanguageSession;
import fina2.dcs.system.SysString;
import fina2.dcs.system.SysStringLocal;
import fina2.dcs.system.SysStringPk;

@Stateful
@Name("returnVersionSession")
@LocalBinding(jndiBinding = "ReturnVersionSession/local")
@Scope(ScopeType.SESSION)
@SuppressWarnings("unchecked")
@AutoCreate
public class ReturnVersionSession implements ReturnVersionLocal,Serializable {

	@PersistenceContext
	private EntityManager em;
	
	@Logger
	private Log log;
	
	private InitialContext ic = null;

	private SysStringLocal sysStringLocal = null;

	@DataModel
	private List<ReturnVersion> returnVersions = new ArrayList<ReturnVersion>();

	private ReturnVersion retVersion = new ReturnVersion();

	private String code = null;

	private boolean success = false;

	private ReturnVersion selectedRetVersion = new ReturnVersion();

	private String selectedDesc = null;

	private final BigDecimal defaultIndex = new BigDecimal("1");

	public void init() {
		log.info("Initializing Return Versions...");
		try {
			ic =ContextHelper.getInitialContext();
			sysStringLocal = ContextHelper.injectSysStringLocal(ic);

			returnVersions = em.createQuery("FROM " + ReturnVersion.class.getName() + " r ORDER BY r.code ASC").getResultList();

			List<BigDecimal> retVersionsDescStrIds = new ArrayList<BigDecimal>();

			for (int i = 0; i < returnVersions.size(); i++)
				retVersionsDescStrIds.add(returnVersions.get(i).getDescStrId());

			StringBuffer sb = new StringBuffer(retVersionsDescStrIds.toString());
			sb.replace(0, 1, "");
			sb.replace(sb.toString().length() - 1, sb.toString().length(), "");

			List<SysString> descriptions = sysStringLocal.getAllValues(sb.toString(), LanguageSession.langId);

			for (int i = 0; i < returnVersions.size(); i++)
				for (int j = 0; j < descriptions.size(); j++) {
					if (returnVersions.get(i).getDescStrId().equals(descriptions.get(j).getPk().getId())) {
						returnVersions.get(i).setDescription(descriptions.get(j).getValue());
						break;
					}
				}

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	public String addReturnVersion() {
		log.info("Adding Return Version " + retVersion.getCode());
		try {
			retVersion.setId(getMaxId().add(defaultIndex));
			retVersion.setDescStrId(sysStringLocal.getMaxId().add(defaultIndex));
			retVersion.setSequence(getMaxSequenceId().add(defaultIndex));
			em.persist(retVersion);

			SysString desc = new SysString();
			SysStringPk descPk = new SysStringPk();
			descPk.setId(retVersion.getDescStrId());
			descPk.setLangId(LanguageSession.langId);
			desc.setValue(retVersion.getDescription());
			desc.setPk(descPk);
			sysStringLocal.addString(desc);
			success = true;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		} finally {
			retVersion = new ReturnVersion();
		}
		return "returnVersionAdded";
	}

	public String updateReturnVersion() {
		try {
			selectedRetVersion = em.merge(selectedRetVersion);
			SysStringPk pk = new SysStringPk(selectedRetVersion.getDescStrId(), LanguageSession.langId);

			SysString ss = sysStringLocal.findByPk(pk);
			ss.setValue(selectedDesc);
			sysStringLocal.updateString(ss);
			success = true;
			
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		} finally {
			selectedRetVersion = new ReturnVersion();
			selectedDesc = null;
		}
		return "returnVersionUpdated";
	}

	public String removeReturnVersion() {
		log.info("Removing Return Version " + code);
		try {
			ReturnVersion rv = findByCode(code);
			SysStringPk pk = new SysStringPk(rv.getDescStrId(),LanguageSession.langId);
			sysStringLocal.removeString(pk);
			if (rv != null)
				em.remove(rv);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		} finally {
			code = null;
		}
		return "returnVersionRemoved";
	}

	public ReturnVersion findByCode(String code) {
		log.info("Searching Return version with code " + code);
		ReturnVersion rv = null;
		try {
			rv = (ReturnVersion) em.createQuery("FROM " + ReturnVersion.class.getName() + " r WHERE RTRIM(r.code)=?").setParameter(1, code).getSingleResult();
		} catch (NoResultException ex) {
			log.info("Could not find return version " + code);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return rv;
	}

	public BigDecimal getMaxId() {
		BigDecimal maxId = new BigDecimal("0");
		try {
			maxId = (BigDecimal) em.createQuery("SELECT MAX(id) FROM " + ReturnVersion.class.getName() + " r").getSingleResult();
			if (maxId == null)
				maxId = defaultIndex;
		} catch (NoResultException ex) {
			maxId = defaultIndex;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return maxId;
	}

	public BigDecimal getMaxSequenceId() {
		BigDecimal maxSeqId = new BigDecimal("0");
		try {
			maxSeqId = (BigDecimal) em.createQuery("SELECT MAX(sequence) FROM " + ReturnVersion.class.getName() + " r").getSingleResult();
			if (maxSeqId == null)
				maxSeqId = defaultIndex;
		} catch (NoResultException ex) {
			maxSeqId = defaultIndex;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return maxSeqId;
	}

	

	@Remove
	@Destroy
	public void remove() {

	}

	public List<ReturnVersion> getReturnVersions() {
		return returnVersions;
	}

	public void setReturnVersions(List<ReturnVersion> returnVersions) {
		this.returnVersions = returnVersions;
	}

	public ReturnVersion getRetVersion() {
		return retVersion;
	}

	public void setRetVersion(ReturnVersion retVersion) {
		this.retVersion = retVersion;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public ReturnVersion getSelectedRetVersion() {
		return selectedRetVersion;
	}

	public void setSelectedRetVersion(ReturnVersion selectedRetVersion) {
		UIComponentHelper.clearComponent(FacesContext.getCurrentInstance().getViewRoot());
		success = false;
		this.selectedRetVersion = selectedRetVersion;
		selectedDesc = selectedRetVersion.getDescription();
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public String getSelectedDesc() {
		return selectedDesc;
	}

	public void setSelectedDesc(String selectedDesc) {
		this.selectedDesc = selectedDesc;
	}

}
